<template>
  <view class="content">
    <view class="header">
      <text class="newyork">新乡</text>
      <view class="search-container">
        <view class="search-box">
          <uni-icons
            type="search"
            style="margin-left: 2%"
            size="20"
            color="#777777"
          ></uni-icons>
          <input
            class="search-input"
            placeholder="请输入搜索内容"
            v-model="searchKeyword"
          />
          <view class="search-button" @click="handleSearch"> 搜索 </view>
        </view>
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="swiper-container">
      <swiper
        class="swiper"
        indicator-dots
        autoplay
        interval="5000"
        duration="1000"
        circular
      >
        <swiper-item v-for="(item, index) in swiperList" :key="index">
          <image :src="item.img" class="swiper-image" mode="aspectFill"></image>
        </swiper-item>
      </swiper>
    </view>

    <!-- 图标区域 -->
    <view class="icons-container">
      <view class="icons-row">
        <view
          class="icon-item"
          v-for="(item, index) in firstRowIcons"
          :key="index"
          @click="handleIconClick(item)"
        >
          <image :src="item.icon" class="icon-image"></image>
          <text class="icon-text">{{ item.title }}</text>
        </view>
      </view>
      <view class="icons-row">
        <view
          class="icon-item"
          v-for="(item, index) in secondRowIcons"
          :key="index"
          @click="handleIconClick(item)"
        >
          <image :src="item.icon" class="icon-image"></image>
          <text class="icon-text">{{ item.title }}</text>
        </view>
      </view>
    </view>

   <!-- 活动 -->
    <view class="activity-container">
      <view class="activity-left">
        <view class="activity-item">
          <image
            class="activity-image"
            :src="getImageUrl('/img/img14830118a93c88290.png')"
          ></image>
          <text>局长信箱</text>
          <view class="go-button" style="color: #87A0FE;">go</view>
          <image
            class="icon-letter"
            :src="getImageUrl('/img/letter.png')"
            mode="scaleToFill"
          />
        </view>
        <view class="activity-item">
          <image
            class="activity-image"
            :src="getImageUrl('/img/img14830418a93ca0930.png')"
          ></image>
          <text>政策咨询</text>
          <view class="go-button" style="color: #00D0C7;">go</view>
          <image
            class="icon-book"
            :src="getImageUrl('/img/book.png')"
            mode="scaleToFill"
          />
        </view>
      </view>
      <view class="activity-right">
        <view class="activity-item">
          <image
            class="activity-image"
            :src="getImageUrl('/img/img15569318aa7917390.png')"
          ></image>
          <text style="margin-left: 12%; width: 100%; top: 14%"
            >志愿者中心</text
          >
          <image
            :src="getImageUrl('/img/volunteer.png')"
            mode="scaleToFill"
            style="
              width: 54px;
              height: 56px;
              position: absolute;
              bottom: 40%;
              right: 30%;
            "
          />
          <view class="go-button" style="#FF88B2">go</view>
        </view>
      </view>
    </view>

    <!-- 特价团购瀑布流 -->
    <view class="waterfall-container">
      <view class="waterfall-header">
		<image
            :src="getImageUrl('/img/img15925318aacafff90.png')"
            mode="scaleToFill"
            style="width: 24px; height: 24px"
          />
        <text class="section-title">
          特价团购</text
        >
      </view>
      <view class="waterfall-content">
        <view class="waterfall-column" :style="{ width: columnWidth + 'px' }">
          <view
  class="waterfall-item"
  v-for="(item, index) in leftColumn"
  :key="'left' + index"
  @click="goToFoodDetail(item)"
>
            <image :src="getProductImage(item)" class="item-image"></image>
            <view class="item-info">
              <text class="item-title">{{ getProductTitle(item) }}</text>
              <view class="item-details-container">
                <text class="item-notice">{{ getProductNotice(item) }}</text>
                <text class="item-quantity">已售: {{ getProductQuantity(item) }}</text>
              </view>
              <view class="item-price-container">
                <text class="item-price">￥{{ getProductPrice(item) }}</text>
                <text class="item-original-price"
                  >￥{{ getProductOriginalPrice(item) }}</text
                >
              </view>
            </view>
          </view>
        </view>
        <view class="waterfall-column" :style="{ width: columnWidth + 'px' }">
          <view
  class="waterfall-item"
  v-for="(item, index) in rightColumn"
  :key="'right' + index"
  @click="goToFoodDetail(item)"
>
            <image :src="getProductImage(item)" class="item-image"></image>
            <view class="item-info">
              <text class="item-title">{{ getProductTitle(item) }}</text>
              <view class="item-details-container">
                <text class="item-notice">{{ getProductNotice(item) }}</text>
                <text class="item-quantity">销量: {{ getProductQuantity(item) }}</text>
              </view>
              <view class="item-price-container">
                <text class="item-price">￥{{ getProductPrice(item) }}</text>
                <text class="item-original-price"
                  >￥{{ getProductOriginalPrice(item) }}</text
                >
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import uniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import config from "@/static/config.js";
// 引入统一封装的API
import { homeAPI } from '../../static/indexAPI.js';

export default {
  components: {
    uniIcons,
  },
  data() {
    return {
      // ... existing code ...
      iconList: [
        {
          icon: this.getImageUrl("/img/icons1.png"),
          title: "美食团购",
          id: 1,
        },
        {
          icon: this.getImageUrl("/img/icons2.png"),
          title: "休闲中心",
          id: 2,
        },
        {
          icon: this.getImageUrl("/img/icons3.png"),
          title: "景区景点",
          id: 3,
        },
        {
          icon: this.getImageUrl("/img/icons4.png"),
          title: "酒店民宿",
          id: 4,
        },
        {
          icon: this.getImageUrl("/img/icons5.png"),
          title: "创业之家",
          id: 5,
        },
        {
          icon: this.getImageUrl("/img/icons6.png"),
          title: "民宿乡情",
          id: 6,
        },
        {
          icon: this.getImageUrl("/img/icons7.png"),
          title: "积分商城",
          id: 7,
        },
        {
          icon: this.getImageUrl("/img/icons8.png"),
          title: "留言信箱",
          id: 8,
        },
      ],
      notice: null,
      productList: [],
      columnWidth: 150, // 列宽，根据屏幕宽度动态计算
    };
  },
  onLoad() {
    wx.hideHomeButton();
    // 检查本地存储中是否有用户信息
    const userinfo = uni.getStorageSync("token");
    if (!userinfo) {
      // 如果没有用户信息，跳转到登录页
      uni.redirectTo({
        url: "/pages/login/login",
      });
    }

    // 计算瀑布流列宽
    const systemInfo = uni.getSystemInfoSync();
    // 假设左右间距各10px，中间间距10px
    this.columnWidth = (systemInfo.windowWidth - 30) / 2;

    // 获取首页数据
    this.getHomeData();
    
    // 在首页加载时设置 tabBar 图标
    this.checkAndSetTabBarIcons();
  },
  computed: {
    firstRowIcons() {
      return this.iconList.slice(0, 4);
    },
    secondRowIcons() {
      return this.iconList.slice(4, 8);
    },
    leftColumn() {
      return this.productList.filter((item, index) => index % 2 === 0);
    },
    rightColumn() {
      return this.productList.filter((item, index) => index % 2 === 1);
    },
  },
   methods: {
    // 获取图片完整URL的方法
    // 获取图片完整URL的方法
    // 获取图片完整URL的方法
    getImageUrl(imgPath) {
      // 如果图片路径已经是完整URL，则直接返回
      if (/^https?:\/\//i.test(imgPath)) {
        return imgPath;
      }
      
      // 如果配置了图片服务器且不是空字符串，则使用配置的图片服务器
      if (config && config.imgUrl) {
        // 确保imgUrl末尾没有斜杠，imgPath开头有斜杠
        let baseUrl = config.imgUrl;
        if (baseUrl.endsWith('/')) {
          baseUrl = baseUrl.slice(0, -1);
        }
        
        // 确保imgPath以斜杠开头
        if (!imgPath.startsWith('/')) {
          imgPath = '/' + imgPath;
        }
        
        const fullUrl = baseUrl + imgPath;
        return fullUrl;
      }
      
      // 否则返回默认图片占位符或空字符串
      return '../../static/logo.png';
    },
    
    // 获取完整的图片URL（增强版）
    getFullImageUrl(imgUrl) {
      if (!imgUrl) return '../../static/logo.png';

      // 如果已经是完整URL，直接返回
      if (/^https?:\/\//i.test(imgUrl)) {
        return imgUrl;
      }

      // 处理相对路径
      let cleanUrl = imgUrl;
      const baseUrl = config.imgUrl || config.baseURL;
      
      // 移除可能重复的基础URL
      while (cleanUrl.startsWith(baseUrl)) {
        cleanUrl = cleanUrl.substring(baseUrl.length);
      }

      // 构造完整URL
      if (cleanUrl.startsWith('/')) {
        return baseUrl + cleanUrl;
      }
      return baseUrl + '/' + cleanUrl;
    },
    // 检查并设置 tabBar 图标
    async checkAndSetTabBarIcons() {
      const isDownloaded = uni.getStorageSync('tabbar_icons_downloaded');
      if (!isDownloaded) {
        // 检查是使用本地图标还是网络图标
        const app = getApp();
        if (typeof app.setLocalTabBarIcons === 'function') {
          // 使用本地图标
          app.setLocalTabBarIcons();
          uni.setStorageSync('tabbar_icons_downloaded', true);
        } else if (typeof app.downloadTabBarIcons === 'function') {
          // 如果没有本地设置方法，则尝试下载网络图标
          await app.downloadTabBarIcons();
        } else {
          // 直接设置本地图标
          this.setLocalTabBarIcons();
          uni.setStorageSync('tabbar_icons_downloaded', true);
        }
      }
      
      // 设置图标
      this.setLocalTabBarIcons();
    },
    
    // 设置本地 tabBar 图标
    setLocalTabBarIcons() {
      // 设置首页图标
      uni.setTabBarItem({
        index: 0,
        iconPath: "static/tabbar_icons/img9352118ca4c9f4a0.png",
        selectedIconPath: "static/tabbar_icons/img9357018ca4d074b0.png"
      });
      
      // 设置娱乐图标
      uni.setTabBarItem({
        index: 1,
        iconPath: "static/tabbar_icons/img9354918ca4ccdad0.png",
        selectedIconPath: "static/tabbar_icons/img9351618ca4c96800.png"
      });
      
      // 设置购物车图标
      uni.setTabBarItem({
        index: 2,
        iconPath: "static/tabbar_icons/img9351118ca4c8eee8.png",
        selectedIconPath: "static/tabbar_icons/img9356218ca4cee640.png"
      });
      
      // 设置个人中心图标
      uni.setTabBarItem({
        index: 3,
        iconPath: "static/tabbar_icons/img9350918ca4c8c7d8.png",
        selectedIconPath: "static/tabbar_icons/img9354518ca4cc9480.png"
      });
    },
    
    // 获取首页数据
    getHomeData() {
      homeAPI.getHomeData().then((res) => {
        if (res.data.code === 1) {
          this.swiperList = res.data.data.swiper || [];
          this.notice = res.data.data.notice || null;
          // 使用首页接口返回的list字段作为团购数据
          this.productList = res.data.data.list || [];


          // 处理图片路径
          this.swiperList.forEach((item) => {
            if (item.img && !item.img.startsWith("http")) {
              item.img = config.baseURL + item.img;
            }
          });

          // 处理商品图片路径
          this.productList.forEach((item) => {
            if (item.img && !item.img.startsWith("http")) {
              item.img = config.baseURL + item.img;
            }
          });
        } else {
          uni.showToast({
            title: res.data.msg || "获取数据失败",
            icon: "none",
          });
        }
      }).catch((err) => {
        uni.showToast({
          title: "网络请求失败",
          icon: "none",
        });
      });
    },
    
    // 获取完整的图片URL
    getFullImageUrl(imgUrl) {
      if (!imgUrl) return '';

      // 如果已经是完整URL，直接返回
      if (/^https?:\/\//i.test(imgUrl)) {
        return imgUrl;
      }

      // 处理相对路径
      let cleanUrl = imgUrl;
      const baseUrl = config.baseURL;
      
      // 移除可能重复的基础URL
      while (cleanUrl.startsWith(baseUrl)) {
        cleanUrl = cleanUrl.substring(baseUrl.length);
      }

      // 构造完整URL
      if (cleanUrl.startsWith('/')) {
        return baseUrl + cleanUrl;
      }
      return baseUrl + '/' + cleanUrl;
    },

    // 获取商品图片
    getProductImage(product) {
      // 判断是否存在food数据，如果存在则使用food中的图片，否则使用外层图片
      let img = null;
      if (product.food && product.food.img) {
        img = product.food.img;
      } else if (product.img) {
        img = product.img;
      }
      
      if (img) {
        return this.getFullImageUrl(img);
      }
      // 默认图片
      return (config && config.imgUrl ? config.imgUrl : '') + "/eat.png";
    },

    // 获取商品标题
    getProductTitle(product) {
      // 判断是否存在food数据，如果存在则使用food中的标题，否则使用外层标题
      if (product.food && product.food.title) {
        return product.food.title;
      } else if (product.title) {
        return product.title;
      }
      return "未知商品";
    },

    // 获取商品详情
    getProductNotice(product) {
      // 判断是否存在food数据，如果存在则使用food中的详情，否则使用外层详情
      if (product.food && product.food.notice) {
        return product.food.notice;
      } else if (product.notice) {
        return product.notice;
      }
      return "暂无详情";
    },

    // 获取商品销量
    getProductQuantity(product) {
      // 判断是否存在food数据，如果存在则使用food中的销量，否则使用外层销量
      if (product.food && product.food.quantity !== undefined) {
        return product.food.quantity;
      } else if (product.quantity !== undefined) {
        return product.quantity;
      }
      return 0;
    },

    // 获取商品价格
    getProductPrice(product) {
      // 判断是否存在food数据，如果存在则使用food中的价格，否则使用外层价格
      if (product.food && product.food.money) {
        return product.food.money;
      } else if (product.food && product.food.price) {
        return product.food.price;
      } else if (product.money) {
        return product.money;
      } else if (product.price) {
        return product.price;
      }
      return "0";
    },

    // 获取商品原价（目前使用现价作为原价，实际项目中应从接口获取）
    getProductOriginalPrice(product) {
      const price = this.getProductPrice(product);
      // 这里简单地将原价设置为现价的1.2倍，实际项目中应该从接口获取
      return (parseFloat(price) * 1.2).toFixed(2);
    },
    
    handleIconClick(item) {
      if (item.id === 1) { // 美食团购
        uni.navigateTo({
          url: '/pages/eat/eat'
        });
      }
      // 其他图标点击处理可以在这里添加
    },
    
    // 跳转到食品详情页
    goToFoodDetail(item) {
      let productId = null;
      
      // 判断是否存在food数据，如果存在则使用food中的商品id，否则使用外层id
      if (item.food && item.food.id) {
        productId = item.food.id;
      } else if (item.id) {
        productId = item.id;
      }
      
      if (productId) {
        // 将商品信息存储到本地
        uni.setStorageSync('currentProduct', item);
        uni.navigateTo({
          url: '/pages/foodDetail/foodDetail?id=' + productId
        });
      } else {
        uni.showToast({
          title: '商品信息有误',
          icon: 'none'
        });
      }
    },
    
    handleSearch() {
      // 搜索功能实现
      uni.showToast({
        title: '搜索功能开发中',
        icon: 'none'
      });
    }
  },
};
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 20rpx;
  padding-bottom: 120rpx; /* 添加底部边距避免被导航栏遮挡 */
}

.header {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.newyork {
  font-size: 36rpx;
  font-weight: bold;
  margin-right: 20rpx;
}

.search-container {
  flex: 1;
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 40rpx;
  border: #ffd000 solid 1px;
}

.search-input {
  flex: 1;
  height: 60rpx;
  background-color: transparent;
  border: none;
  padding: 6px 20rpx;
  font-size: 28rpx;
  outline: none;
}

.search-button {
  width: 70rpx;
  height: 50rpx;
  background-color: #ffd000;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 30rpx;
  padding: 5px 8px;
}

.swiper-container {
  width: 100%;
  margin-bottom: 30rpx;
}

.swiper {
  height: 300rpx;
  border-radius: 15rpx;
}

.swiper-image {
  width: 100%;
  height: 100%;
}

.icons-container {
  width: 100%;
  margin-bottom: 30rpx;
}

.icons-row {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin-bottom: 20rpx;
}

.icons-row:last-child {
  margin-bottom: 0;
}

.icon-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 25%;
}

.icon-image {
  width: 96rpx;
  height: 90rpx;
  /* border-radius: 50%; */
  margin-bottom: 10rpx;
}

.icon-text {
  font-size: 24rpx;
  color: #333333;
}

.notice-container {
  width: 100%;
  background-color: #ffffff;
  border-radius: 15rpx;
  padding: 20rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.notice-header {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.notice-icon {
  width: 40rpx;
  height: 40rpx;
}

.notice-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-left: 10rpx;
}

.notice-list {
  padding-left: 10rpx;
}

.notice-item {
  margin-bottom: 10rpx;
}

.notice-text {
  font-size: 24rpx;
  color: #666666;
}

.activity-container {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.activity-left {
  width: 60%;
  height: 220px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.activity-right {
  width: 38%;
  height: 220px;
  display: flex;
  flex-direction: column;
}

.activity-image {
  width: 100%;
  border-radius: 15rpx;
}

.activity-item {
  position: relative;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.activity-item .activity-image {
  flex: 1;
  margin-bottom: 20rpx;
}

.activity-item:last-child .activity-image {
  margin-bottom: 0;
}

.activity-item text {
  position: absolute;
  top: 24%;
  left: 31%;
  transform: translate(-50%, -50%);
  color: white;
}

.go-button {
  position: absolute;
  bottom: 44rpx;
  left: 36rpx;
  background-color: white;
  border-radius: 25rpx;
  padding: 10rpx 30rpx;
  color: #666666;
  z-index: 2;
}

.icon-letter,
.icon-book {
  position: absolute;
  bottom: 34rpx;
  right: 32rpx;
  width: 101rpx;
  height: 88rpx;
  z-index: 2;
}

.activity-container text {
  display: block;
  text-align: center;
  margin-top: 5rpx;
  font-size: 44rpx;
  color: #fff;
}
.waterfall-container {
  width: 100%;
}

.waterfall-header {
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333333;
  margin-left: 10rpx;
}

.waterfall-content {
  display: flex;
  justify-content: space-between;
}

.waterfall-column {
  display: flex;
  flex-direction: column;
}

.waterfall-item {
  width: 95%;
  background-color: #ffffff;
  border-radius: 15rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.item-image {
  width: 100%;
  height: 210rpx;
}

.item-info {
  padding: 15rpx;
}

.item-title {
  font-size: 26rpx;
  color: #333333;
  margin-bottom: 10rpx;
  display: block;
  font-weight: bold;
}

.item-details-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.item-notice {
  font-size: 22rpx;
  color: #666666;
  flex: 0 0 45%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-quantity {
  font-size: 22rpx;
  color: #999999;
  text-align: right;
  flex: 1;
  margin-left: 10rpx;
}

.item-price-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.item-price {
  font-size: 30rpx;
  color: #FF8D1A;
  font-weight: bold;
}

.item-original-price {
  font-size: 24rpx;
  color: #999999;
  text-decoration: line-through;
}
</style>